package com.bnyy.medicalHousekeeper.fragment;

import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.viewpager2.widget.ViewPager2;

import com.blankj.utilcode.util.SpanUtils;
import com.bnyy.common.view.AAChartCoreLib.AAChartCreator.AAChartModel;
import com.bnyy.common.view.AAChartCoreLib.AAChartCreator.AAChartView;
import com.bnyy.common.view.AAChartCoreLib.AAChartCreator.AASeriesElement;
import com.bnyy.common.view.AAChartCoreLib.AAChartEnum.AAChartStackingType;
import com.bnyy.common.view.AAChartCoreLib.AAChartEnum.AAChartSymbolStyleType;
import com.bnyy.common.view.AAChartCoreLib.AAChartEnum.AAChartSymbolType;
import com.bnyy.common.view.AAChartCoreLib.AAChartEnum.AAChartType;
import com.bnyy.common.view.AAChartCoreLib.AAOptionsModel.AAMarker;
import com.bnyy.common.view.AAChartCoreLib.AAOptionsModel.AAOptions;
import com.bnyy.common.view.AAChartCoreLib.AAOptionsModel.AASeries;
import com.bnyy.common.view.AAChartCoreLib.AAOptionsModel.AASeriesEvents;
import com.bnyy.common.view.AAChartCoreLib.AAOptionsModel.AAStyle;
import com.bnyy.common.view.AAChartCoreLib.AAOptionsModel.AATooltip;
import com.bnyy.common.view.AAChartCoreLib.AAOptionsModel.AAYAxis;
import com.bnyy.common.view.AAChartCoreLib.AATools.AAColor;
import com.bnyy.common.view.AAChartCoreLib.AATools.AAGradientColor;
import com.bnyy.common.view.AAChartCoreLib.AATools.AALinearGradientDirection;
import com.bnyy.medicalHousekeeper.PopupWindowHelper;
import com.bnyy.medicalHousekeeper.R;
import com.bnyy.medicalHousekeeper.activity.ScanQrcodeActivity;
import com.bnyy.medicalHousekeeper.adapter.IndexStatsAdapter;
import com.bnyy.medicalHousekeeper.base.App;
import com.bnyy.medicalHousekeeper.base.BaseFragmentImpl;
import com.bnyy.medicalHousekeeper.bean.IndexData;
import com.bnyy.medicalHousekeeper.bean.IndexStats;
import com.bnyy.medicalHousekeeper.request.BaseObserverImpl;
import com.bnyy.medicalHousekeeper.request.RequestManager;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;
import com.google.gson.Gson;
import com.littlejerk.rvdivider.builder.XGridBuilder;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.function.Consumer;

import butterknife.BindView;

/**
 * Author : 关炳鹏
 * Description :
 * Date : 2023/2/2
 **/
public class IndexFragment extends BaseFragmentImpl {
    @BindView(R.id.tv_rold)
    TextView tvRold;
    @BindView(R.id.tv_date)
    TextView tvDate;
    @BindView(R.id.chart_view)
    AAChartView chartView;
    @BindView(R.id.recycler_view)
    RecyclerView recyclerView;
    @BindView(R.id.tv_withdrawable)
    TextView tvWithdrawable;
    @BindView(R.id.tv_frozen_income)
    TextView tvFrozenIncome;
    @BindView(R.id.tv_accumulated_income)
    TextView tvAccumulatedIncome;
    @BindView(R.id.ll_index_data_types)
    LinearLayout llIndexDataTypes;
    @BindView(R.id.refresh_layout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.iv_scan)
    ImageView ivScan;

    private IndexStatsAdapter adapter;

    @Override
    public int getLayoutId() {
        return R.layout.fragment_index;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return super.onCreateView(inflater, container, savedInstanceState);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        sdfyyyyMMddHHmmss = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        sdfMMdd = new SimpleDateFormat("MM/dd");

        recyclerView.setLayoutManager(new GridLayoutManager(mContext, 3));

        recyclerView.addItemDecoration(new XGridBuilder(mContext)
                .setSpacing(12F)
                .setColor(Color.WHITE)
                .build());
        adapter = new IndexStatsAdapter(mContext);
        recyclerView.setAdapter(adapter);

        date = sdfyyyyMMddHHmmss.format(new Date());

        tvDate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Calendar calendar = Calendar.getInstance();
                calendar.set(2020, 1, 1);
                PopupWindowHelper.getInstance(mContext).showSelectTimePopupWindow(PopupWindowHelper.SelectDateTime.TYPE_YM,
                        "", calendar.getTimeInMillis(), System.currentTimeMillis(), true,
                        new PopupWindowHelper.SelectDateTime.OnSelectTimeListener() {
                            @Override
                            public void onSelected(String formatTime, long timeMillis, int y, int m, int d, int h, int min) {
                                date = sdfyyyyMMddHHmmss.format(new Date(timeMillis));
                                getIndexStats(null);
                            }
                        });
            }
        });
        ivScan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ScanQrcodeActivity.show(mContext);
            }
        });
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                getIndexStats(refreshLayout);

                getIndexData();
            }
        });
        refreshLayout.autoRefresh();
    }

    private String date;
    private SimpleDateFormat sdfyyyyMMddHHmmss;
    private SimpleDateFormat sdfMMdd;

    private void getIndexStats(RefreshLayout refreshLayout) {
        try {
            tvDate.setText(new SimpleDateFormat("yyyy-MM").format(sdfyyyyMMddHHmmss.parse(date)));
        } catch (ParseException e) {
            e.printStackTrace();
        }

        HashMap<String, Object> params = new HashMap<>();
        params.put("role_id", App.getRoleId());
        params.put("date", date);
        requestManager.request(requestManager.mJavaRetrofitService.getIndexStats(RequestManager.getJsonRequestBody(params)),
                new BaseObserverImpl<IndexStats>(refreshLayout) {
                    @Override
                    public void onSuccess(IndexStats indexStats) {
                        super.onSuccess(indexStats);

                        adapter.refresh(indexStats.getStatsSubjects());

                        ArrayList<IndexStats.StatsDetail> details = indexStats.getStatsDetails();

                        try {

                            Object[] datas = new Object[details.size()];
                            String[] xValues = new String[details.size()];
                            int max = 0;
                            for (int i = 0; i < datas.length; i++) {
                                IndexStats.StatsDetail statsDetail = details.get(i);
                                int value = Integer.parseInt(statsDetail.getValue());

                                if (value > max) {
                                    max = value;
                                }

                                xValues[i] = (i + 1) + "";

                                HashMap<String, Object> params = new HashMap<>();
                                params.put("y", value);
                                params.put("date", sdfMMdd.format(sdfyyyyMMddHHmmss.parse(statsDetail.getDate())));
                                datas[i] = params;
                            }

                            AAChartModel aaChartModel = new AAChartModel()
                                    .categories(xValues)
                                    .dataLabelsEnabled(false)//是否显示值
                                    .xAxisLabelsEnabled(true)
                                    .touchEventEnabled(true)
                                    .stacking(AAChartStackingType.Normal)
                                    .yAxisVisible(true)
                                    .markerSymbolStyle(AAChartSymbolStyleType.InnerBlank)
                                    .series(new AASeriesElement[]{
                                            new AASeriesElement()
                                                    .name("新增订单")
                                                    .type(AAChartType.Areaspline)
                                                    .lineWidth(1.5f)
                                                    .marker(new AAMarker()
                                                            .symbol(AAChartSymbolType.Circle)
                                                            .radius(0f)
                                                    )
                                                    .color("#FFCC3E")
                                                    .fillColor(AAGradientColor.linearGradient(
                                                            AALinearGradientDirection.ToBottom,
                                                            new Object[][]{
                                                                    {0.0, AAColor.rgbaColor(255, 204, 62, 0.6f)},//颜色字符串设置支持十六进制类型和 rgba 类型
                                                                    {0.5, AAColor.rgbaColor(255, 204, 62, 0.3f)},
                                                                    {1.0, AAColor.rgbaColor(255, 204, 62, 0.0f)}
                                                            }
                                                    ))
                                                    .data(datas),
                                    });

                            AAOptions aaOptions = aaChartModel.aa_toAAOptions();
                            aaOptions.legend.enabled(false);
                            aaOptions.xAxis.tickInterval = 3;
                            AAYAxis yAxis = aaOptions.yAxis;
                            aaOptions.yAxis
                                    .allowDecimals(false)
                                    .min(0F)
                                    .max(max == 0 ? 10F : (float) max);

                            AATooltip aaTooltip = new AATooltip();
                            aaTooltip.style(new AAStyle()
                                    .fontSize(10)
                                    .padding(0))
                                    .formatter("function () {" +
                                            "let myPointOptions = this.points[0].point.options;" +
                                            "let s = this.x + '<br/>';" +
                                            "let colorDot1 = '<span style=\\\"' + 'color:#FFCC3E; font-size:8px\\\"' + '>●</span> ';" +
//                                            "let s1 = colorDot1 + this.points[0].series.name + ': ' + myPointOptions.y;" +
                                            "let s1 = colorDot1 + myPointOptions.date + ': ' + myPointOptions.y;" +
                                            "return s1;" +
                                            "}")
                                    .valueDecimals(2);//设置取值精确到小数点后几位//设置取值精确到小数点后几位
                            aaOptions.tooltip(aaTooltip);

                            aaOptions.plotOptions.series(new AASeries()
                                    .connectNulls(true)
                                    .events(new AASeriesEvents()
                                            .legendItemClick(" function () {" +
                                                    "return false;" +
                                                    "}"))
                            );
                            chartView.aa_drawChartWithChartOptions(aaOptions);
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    private void getIndexData() {
        HashMap<String, Object> params = new HashMap<>();
        params.put("role_id", 4001);
        requestManager.request(requestManager.mJavaRetrofitService.getIndexData(RequestManager.getJsonRequestBody(params)),
                new BaseObserverImpl<IndexData>() {
                    @Override
                    public void onSuccess(IndexData indexData) {
                        super.onSuccess(indexData);

                        DecimalFormat decimalFormat = new DecimalFormat("#0.00");
                        int grayLight = ContextCompat.getColor(mContext, R.color.gray_light);
                        SpanUtils.with(tvWithdrawable)
                                .append(decimalFormat.format(indexData.getWithdrawal_money())).setBold()
                                .appendLine()
                                .appendLine()
                                .append("可提现").setForegroundColor(grayLight)
                                .create();

                        SpanUtils.with(tvFrozenIncome)
                                .append(decimalFormat.format(indexData.getFrozen_money())).setBold()
                                .appendLine()
                                .appendLine()
                                .append("冻结收益").setForegroundColor(grayLight)
                                .create();

                        SpanUtils.with(tvAccumulatedIncome)
                                .append(decimalFormat.format(indexData.getTotal_money())).setBold()
                                .appendLine()
                                .appendLine()
                                .append("累计收益").setForegroundColor(grayLight)
                                .create();

                        llIndexDataTypes.removeAllViews();

                        ArrayList<IndexData.Data> datas = indexData.getDatas();

                        datas.forEach(new Consumer<IndexData.Data>() {
                            @Override
                            public void accept(IndexData.Data data) {
                                View view = inflater.inflate(R.layout.fragment_index_data_types, llIndexDataTypes, false);

                                llIndexDataTypes.addView(view);

                                TabLayout tabLayout = view.findViewById(R.id.tab_layout);
                                tabLayout.setSelectedTabIndicator(null);
                                ViewPager2 viewPager = view.findViewById(R.id.view_pager);

                                ArrayList<IndexData.Data.Type> types = data.getTypes();
                                if (types != null && types.size() > 0) {
                                    viewPager.setAdapter(new FragmentStateAdapter(getChildFragmentManager(), getLifecycle()) {
                                        @NonNull
                                        @Override
                                        public Fragment createFragment(int position) {
                                            IndexData.Data.Type type = types.get(position);
                                            Log.e("createFragment", new Gson().toJson(type));
                                            return IndexDatasFragment.getInstance(types.get(position));
                                        }

                                        @Override
                                        public int getItemCount() {
                                            return types.size();
                                        }
                                    });

                                    TabLayoutMediator mediator = new TabLayoutMediator(tabLayout, viewPager, new TabLayoutMediator.TabConfigurationStrategy() {
                                        @Override
                                        public void onConfigureTab(@NonNull TabLayout.Tab tab, int position) {
                                            tab.setText(types.get(position).getTag_name());
                                        }
                                    });
                                    mediator.attach();
                                }
                            }
                        });
                    }
                });
    }
}































